/*
 * @Author: 严晗 823841034@qq.com
 * @Date: 2023-11-02 16:13:51
 * @LastEditors: 严晗 823841034@qq.com
 * @LastEditTime: 2024-03-02 14:33:08
 * @FilePath: /yike-admin/Users/yanhan/vite-project/src/crud/sale/useDay.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { reactive, ref, toRefs, watchEffect, nextTick } from 'vue'
import { useDicData } from '~/composables/useDicData'
import { getDateRange } from '~/composables/useDate'
import { getDayList } from '~/api/day'
import { exportExcel } from '~/api/public'
import { toast } from '~/composables/utils'

// 搜索项配置
export function useSearchOptions() {
	// 获取当前页面所需的相关字典项数据
	let { salesData, companyAreaData } = useDicData()

	let searchOptions = reactive({
		times: {
			label: '日期',
			component: 'el-date-picker',
			customContent: true,
			type: 'daterange',
			value: getDateRange(), // 当前日期数组
			attrs: {
				format: 'YYYY-MM-DD',
				valueFormat: 'YYYY-MM-DD',
			},
		},
		regionIds: {
			label: '区域',
			component: 'el-tree-select',
			attrs: {
				multiple: true,
				collapseTags: true,
				collapseTagsTooltip: true,
				renderAfterExpand: false,
				showCheckbox: true,
				data: companyAreaData,
				nodeKey: 'id',
				props: {
					label: 'name',
					value: 'id',
				},
			},
		},
		salesId: {
			label: '销售',
			component: 'el-select',
			options: salesData,
		},
	})

	return {
		searchOptions,
	}
}
// 表格配置
export function useTableOptions() {
	// tableOptions 表格基础配置
	// tableTempOptions 表格动态配置，为0时不显示
	const temp = reactive({
		tableOptions: [
			{
				prop: 'dailyDate',
				label: '日期',
				fixed: 'left',
			},
			{
				label: '销售业绩负责人',
				prop: 'salesName',
				minWidth: 110,
				fixed: 'left',
			},
			{
				label: '做单总单数',
				prop: 'yejiNum',
				minWidth: 80,
			},
			{
				label: '业绩总单量',
				prop: 'yejiDiscount',
				minWidth: 80,
			},
			{
				label: '必备业绩单量',
				prop: 'bibeiDiscount',
				minWidth: 90,
			},
			{
				label: '必备业务<br />（单）',
				prop: 'bibeiNum',
				slotHeader: true,
				minWidth: 70,
			},
			{
				label: '抖音极速版<br />（单）',
				prop: 'douyinjsNum',
				slotHeader: true,
				minWidth: 80,
			},
			{
				label: '抖音-IOS<br />（单）',
				prop: 'douyinIosNum',
				slotHeader: true,
				minWidth: 70,
			},
			{
				label: '苹果必备<br />（单）',
				prop: 'bibeiIosNum',
				slotHeader: true,
				minWidth: 70,
			},
			{
				label: '抖音<br />（单）',
				prop: 'douyinNum',
				slotHeader: true,
				minWidth: 60,
			},
			{
				label: '抖音活动<br />（单）',
				prop: 'dyhdNum',
				slotHeader: true,
				minWidth: 70,
			},
			{
				label: '快手极速版<br />（单）',
				prop: 'kuaishouNum',
				slotHeader: true,
				minWidth: 80,
			},
		],
		tableTempOptions: [
			{
				label: '头条极速<br />（单）',
				prop: 'toutiaojsNum',
				slotHeader: true,
				minWidth: 70,
			},
			{
				label: '番茄小说<br />（单）',
				prop: 'fanqiexsNum',
				slotHeader: true,
				minWidth: 70,
			},
			{
				label: '点淘<br />（单）',
				prop: 'diantaoNum',
				slotHeader: true,
				minWidth: 60,
			},
			{
				label: '分发业务<br />（台）',
				prop: 'fenfaNum',
				slotHeader: true,
				minWidth: 70,
			},
			{
				label: '抖音极速版-IOS<br />（单）',
				prop: 'dyjsIosNum',
				slotHeader: true,
				minWidth: 110,
			},
			{
				label: '淘宝特价<br />（单）',
				prop: 'taobaotjNum',
				slotHeader: true,
				minWidth: 70,
			},
			{
				label: '淘宝<br />（单）',
				prop: 'taobaoNum',
				slotHeader: true,
				minWidth: 60,
			},
			{
				label: '美团<br />（单）',
				prop: 'meituanNum',
				slotHeader: true,
				minWidth: 60,
			},
			{
				label: '抖音火山<br />（单）',
				prop: 'douyinhsNum',
				slotHeader: true,
				minWidth: 70,
			},
			{
				label: '百度极速版<br />（单）',
				prop: 'baidujsNum',
				slotHeader: true,
				minWidth: 80,
			},
			{
				label: '快手首购<br />（单）',
				prop: 'kuaishousgNum',
				slotHeader: true,
				minWidth: 70,
			},
			{
				label: '快手关注<br />（单）',
				prop: 'kuaishougzNum',
				slotHeader: true,
				minWidth: 70,
			},
			{
				label: '京东<br />（单）',
				prop: 'jingdongNum',
				slotHeader: true,
				minWidth: 60,
			},
			{
				label: '京喜<br />（单）',
				prop: 'jingxiNum',
				slotHeader: true,
				minWidth: 60,
			},
			{
				label: '西瓜视频<br />（单）',
				prop: 'xiguaspNum',
				slotHeader: true,
				minWidth: 70,
			},
			{
				label: '换机业务<br />（软件数）',
				prop: 'huanjiNum',
				slotHeader: true,
				minWidth: 80,
			},
			{
				label: '必备任务<br />（软件数）',
				prop: 'bbTaskNum',
				slotHeader: true,
				minWidth: 80,
			},
			{
				label: '优酷视频<br />（单）',
				prop: 'ykNum',
				slotHeader: true,
				minWidth: 70,
			},
			{
				label: '热门业务<br />（单）',
				prop: 'hotNum',
				slotHeader: true,
				minWidth: 70,
			},
			{
				label: '亚丁碎屏险<br />（单）',
				prop: 'yadingNum',
				slotHeader: true,
				minWidth: 80,
			},
			{
				label: '亚丁碎屏险业绩单量',
				prop: 'yadingDiscount',
			},
			{
				label: '繁星二手机<br />（单）',
				prop: 'fanxingNum',
				slotHeader: true,
				minWidth: 80,
			},
			{
				label: '繁星二手机业绩单量',
				prop: 'fanxingDiscount',
			},
		],
	})

	const { tableOptions, tableTempOptions } = toRefs(temp)

	return {
		tableOptions,
		tableTempOptions,
	}
}

// 分页配置
export function usePage() {
	// 分页数据
	let page = ref({
		currentPage: 1,
		pageSize: 100,
		total: 0,
		pageSizeOptions: [10, 50, 100, 200],
	})
	const handleSizeChange = (val) => {
		page.value.pageSize = val
	}
	const handleCurrentChange = (val) => {
		page.value.currentPage = val
	}
	return {
		page,
		handleSizeChange,
		handleCurrentChange,
	}
}

// 搜索表单
export function useSearch() {
	// 搜索表单数据
	let searchForm = ref({})
	// 搜索刷新
	let refreshSearchFlag = ref(false)

	// 搜索方法
	const handleSearch = (data) => {
		searchForm.value = data

		// 搜索时使用，用于下面getList监听
		refreshSearchFlag.value = false
		nextTick(() => {
			refreshSearchFlag.value = true
		})
	}

	return {
		searchForm,
		refreshSearchFlag,
		handleSearch,
	}
}

// 表格数据
// 传入参数：分页、搜索表单、表格配置、表格动态配置
export function useTableData(page, searchForm, refreshSearchFlag, tableOptions, tableTempOptions) {
	// 表格数据
	const list = reactive({ tableData: [] })

	// table 组件 ref
	const tablePaginRef = ref(null)

	const loading = ref(false)
	// 获取列表数据
	const getList = () => {
		// 加载状态
		loading.value = true
		// 分页参数
		let params = {
			current: page.value.currentPage,
			size: page.value.pageSize,
			startDailyDate: getDateRange()[0],
			endDailyDate: getDateRange()[1],
		}

		let searchParams = JSON.parse(JSON.stringify(searchForm.value))
		if (searchParams.times && searchParams.times.length) {
			params.startDailyDate = searchParams.times[0]
			params.endDailyDate = searchParams.times[1]
			delete searchParams.times
		}
		if (searchParams.regionIds && searchParams.regionIds.length) {
			params.regionIds = searchParams.regionIds.join()
			delete searchParams.regionIds
		}
		getDayList(Object.assign(params, searchParams))
			.then((res) => {
				list.tableData = res.data.data.records
				page.value.total = res.data.data.total

				// 更新表格配置
				const temp = tableTempOptions.value
				if (tableData.value.length) {
					// temp 数组中的 prop 值 和 tableData 中的属性名一致时，tableData对应的属性值不为0，则将temp中的对象添加到tableOptions中
					for (let i = 0; i < temp.length; i++) {
						// 这里只需要判断 tableData 中的第一条数据即可
						// 第一条数据 为 汇总数据
						if (tableData.value[0][temp[i].prop] !== 0) {
							tableOptions.value.push(temp[i])
						}
					}
				}
				// 加载完成后刷新表格
				nextTick(() => {
					tablePaginRef.value.layout()
				})
			})
			.finally(() => {
				loading.value = false
			})
	}

	// 监听获取列表数据的方法，可以根据该方法中的值变化进行数据处理
	// 监听到getList中的page、searchForm变化时，重新获取列表数据
	watchEffect(() => {
		// 刷新搜索的参数不使用，仅监听而已
		if (refreshSearchFlag.value) {
			getList()
		}
	})

	// 解构表格数据
	const { tableData } = toRefs(list)

	return {
		loading,
		tableData,
		tablePaginRef,
		getList,
	}
}

// 表格左侧按钮配置
export function useTableBtnOptions(searchForm, useExportExcel) {
	const currentBtnLoading = ref(-1)

	const tableLeftBtnOptions = [
		{
			label: '导出明细',
			type: 'primary',
			icon: 'download',
			url: '/data/salesDailyRecord/exportSalesDailyRecord',
		},
	]

	const handleBtnClick = (index) => {
		currentBtnLoading.value = index
		useExportExcel(tableLeftBtnOptions[index].url, searchForm.value)
		// 1.5秒后重置loading状态
		nextTick(() => {
			setTimeout(() => {
				currentBtnLoading.value = -1
			}, 1500)
		})
	}

	return { tableLeftBtnOptions, currentBtnLoading, handleBtnClick }
}

// 导出
export function useExportExcel(url, searchForm) {
	let params = {
		startDailyDate: getDateRange()[0],
		endDailyDate: getDateRange()[1],
	}
	let searchParams = JSON.parse(JSON.stringify(searchForm))
	if (searchParams.times && searchParams.times.length) {
		params.startDailyDate = searchParams.times[0]
		params.endDailyDate = searchParams.times[1]
	}
	exportExcel(url, params).then(() => {
		toast('导出成功')
	})
}
